<?php


namespace app\api\service;

class CommonService
{
	public static function fileUpdate($upload_config, $ip)
	{
		if (!empty($upload_config["max_frequency_limit]"])) {
			if (\think\Db::name("public_upload_log")->where([["ip", "=", $ip], ["addtime", ">=", strtotime(date("Y-m-d"))]])->count() >= $upload_config["max_frequency_limit"]) {
				return ["code" => 10042, "msg" => "今日文件上传过多"];
			}
		}
		$save_dir = "uploads/public_file";
		\think\Db::startTrans();
		try {
			$file = request()->file("file");
			if (!$file) {
				throw new \Exception("请传入文件");
			}
			$validate = [];
			$allow_file_suffix = [];
			if (!empty($upload_config["allow_file_suffix"]) && is_array($upload_config["allow_file_suffix"])) {
				foreach ($upload_config["allow_file_suffix"] as $file_suffix) {
					if (!empty($file_suffix["open"])) {
						$allow_file_suffix[] = $file_suffix["suffix"];
					}
				}
			}
			if ($allow_file_suffix) {
				$validate["ext"] = implode(",", $allow_file_suffix);
			}
			if (!empty($upload_config["max_size_limit"])) {
				$validate["size"] = $upload_config["max_size_limit"] * 1024;
			}
			$info = $file->validate($validate)->move($save_dir);
			if (empty($info)) {
				throw new \Exception($file->getError());
			}
			$data = array_merge(["ip" => $ip, "name" => $file->getInfo("name"), "type" => \app\common\model\File::type_image, "addtime" => time(), "overtime" => time() + 300], handle_file_storage($file, $info, $save_dir));
			$file_id = \think\Db::name("public_upload_log")->insertGetId($data);
			\think\Db::commit();
			return ["code" => \app\api\controller\Code::success, "msg" => "上传成功", "data" => ["file_id" => $file_id]];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\api\controller\Code::error, "msg" => "上传失败 " . $e->getMessage()];
		}
	}
}